﻿using System;
using System.Linq;
using System.Threading.Tasks;
using Atmk.WaterMeter.MIS.Commons.Interfaces.Logic.Statistics;
using Atmk.WaterMeter.MIS.Commons.Interfaces.TimeTask;
using Atmk.WaterMeter.MIS.Entities.Enums;
using Newtonsoft.Json;
using NLog;

namespace Atmk.WaterMeter.MIS.TimedTask.Unused
{
    /// <summary>
    /// 与片区相关的统计任务
    /// </summary>
    public class RegionTask:IRegionTask
    {
        private readonly IRegionLogic _regionLogic;
        private readonly IStatisticHistoryLogic _statisticHistoryLogic;
        private readonly IWaterMetersLogic _waterMetersLogic;
        private static readonly Logger _logger = LogManager.GetCurrentClassLogger();
        public RegionTask(
            IRegionLogic regionLogic,
            IStatisticHistoryLogic statisticHistoryLogic,
            IWaterMetersLogic waterMetersLogic
        )
        {
            _waterMetersLogic = waterMetersLogic;
            _regionLogic = regionLogic;
            _statisticHistoryLogic = statisticHistoryLogic;
        }

        /// <summary>
        /// 执行一便片区统计任务
        /// </summary>
        public void Start(string projectId)
        {
            var task = new Task(() =>
            {
                //统计信息
                var data = _regionLogic.GetStatisticsInfoData(projectId);
                _statisticHistoryLogic.Save(projectId, StatisticType.StatisticsInfoData, data);
                var jsData = JsonConvert.SerializeObject(data);
                _logger.Info(jsData);

                //片区统计
                var districts = _regionLogic.GetLeafDistrictEntities(projectId);
                var distirctIds = districts.Select(d => d.Id).ToArray();
                var districtData =
                    _waterMetersLogic.GetDistrictReadRatioItems(DateTime.Now.AddDays(-1), distirctIds);
                _statisticHistoryLogic.Save(projectId, StatisticType.DistrictReadRatioData, districtData);
                var jsData2 = JsonConvert.SerializeObject(districtData);
                _logger.Info(jsData2);

            });
            task.Start();
        }
    }
}
